﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RequirementBubble : MonoBehaviour
{
    public Transform CountBarParent;
    public SpriteRenderer Icon;
    public Sprite A;
    public Sprite B;
    public Sprite C;
    public Sprite check;
    public Sprite angry;

    ESupplyType requirement;
    int DemandRemainTime;
    int DemandMaxTime;
    bool delay = false;
    bool shouldUnactive = false;
    bool afterDemand = false;
    Villager vg;

    void Start()
    {
        GameManager.Instance.BindToOnMove(OnMove);
    }

    private void OnEnable()
    {
        init();
        shouldUnactive = false;
    }

    private void init()
    {
        vg = transform.parent.GetComponent<Villager>();
        DemandMaxTime = vg.currentDemandMaxTime;
        DemandRemainTime = vg.currentDemandRemainTime;
        requirement = vg.currentDemandType;
        switch (requirement)
        {
            case ESupplyType.Love:
                Icon.sprite = A;
                break;
            case ESupplyType.Game:
                Icon.sprite = B;
                break;
            case ESupplyType.Food:
                Icon.sprite = C;
                break;
        }
    }

    public void OnMove()
    {
        if (delay)
        {
            delay = false;
            shouldUnactive = true;
        }
    }

    void Update()
    {
        DemandMaxTime = vg.currentDemandMaxTime;
        DemandRemainTime = vg.currentDemandRemainTime;
        float scale = 0f;
        if (DemandMaxTime != 0)
            scale = (float)DemandRemainTime / (float)DemandMaxTime;
        if (scale > 0)
            afterDemand = true;
        if (scale < 0)
            scale = 0;
        CountBarParent.localScale = new Vector3(scale, 1f, 1f);
        if(DemandRemainTime == 0)
        {
            CountBarParent.localScale = new Vector3(0, 1f, 1f);
        }
        if(DemandRemainTime == 0 && afterDemand)
        {
            if (shouldUnactive)
            {
                gameObject.SetActive(false);
            }
            else
            {
                Icon.sprite = angry;
                delay = true;
            }
        }

        if(DemandRemainTime == 0 && !afterDemand)
        {
            gameObject.SetActive(false);
        }

        if (vg.demandFulfilled)
        {
            if (shouldUnactive)
            {
                gameObject.SetActive(false);
            }
            else
            {
                Icon.sprite = check;
                delay = true;
            }
        }
    }
};
